<template>
  <div class="seal-order-content">
    <div class="filter-form" style="margin:12px 0;">
      <FilterInput v-if="!showMobilePage" ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" show-search-btn @handelClick="getData(true)" @queryEmpty="queryEmpty" />
      <div v-if="!showMobilePage" class="export-wrap flex-center">
        <topRightAmount :total-tax-amount="list.otherData && list.otherData.totalTaxAmount" title="含税金额" />
        <export-button
          ref="orderExportRef"
          :export-api="'/admin/review/orderList/export'"
          :export-name="'封账订单'"
          is-before-export
          class="btn-right-item"
          is-diy
          style="padding: 0"
          @beforeExport="exportBeforeExport('orderExportRef')"
          @onComplate="exportComplete">
          <el-button
            :disabled="exportLoading"
            :loading="exportLoading"
            class="export-btn"
            size="small"
            type="primary"
            plain>导出</el-button>
        </export-button>
      </div>
      <div v-else class="export-wrap flex-center mobile-export-wrap">
        <topRightAmount :total-tax-amount="list.otherData && list.otherData.totalTaxAmount" title="含税金额" />
        <div class="btn-wrap">
          <FilterInput v-if="showMobilePage" ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" :show-text="false" show-search-btn show-mobile-icon @handelClick="getData(true)" @queryEmpty="queryEmpty" />
          <export-button
            ref="orderExportRef"
            :export-api="'/admin/review/orderList/export'"
            :export-name="'封账订单'"
            is-before-export
            class="btn-right-item"
            is-diy
            style="padding: 0"
            @beforeExport="exportBeforeExport('orderExportRef')"
            @onComplate="exportComplete">
            <img :src="exportImg" class="export-icon" alt="export" >
          </export-button>
        </div>
      </div>
    </div>
    <div class="seal-order-table">
      <el-table
        v-loading="listLoading"
        ref="orderTableRef"
        :data="list.items"
        :header-cell-style="{fontSize: '14px',color: '#141C3D'}"
        :row-class-name="(data) => tableRowClassName(data)"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        fit
        hightlight-current-row
        class="fb-table"
        header-cell-class-name="order-data-header-cell"
        @sort-change="sortMethod"
        @select="selectTable"
        @select-all="selectTable"
        @selection-change="handleSelectionChange">
        <el-table-column
          v-if="!isReport"
          align="left"
          type="selection"
          width="55"
          fixed="left"
        />
        <el-table-column align="left" label="订单编号" min-width="200">
          <template slot-scope="scope">
            <ToolTip v-if="scope.row.orderId" :content="scope.row.orderId">
              <router-link
                :to="{name: 'orderDetail', params: {orderId: scope.row.id}, query: { sealingId }}"
                target="_blank"
                style="color:#406EFF; width: 100%"
                class="order-id ellipsis"
              >{{ scope.row.orderId }}</router-link>
            </ToolTip>
            <span v-else>
              <router-link
                :to="{name: 'orderDetail', params: {orderId: scope.row.id}, query: { sealingId }}"
                target="_blank"
                style="color:#406EFF;"
                class="order-id"
              >--</router-link>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="客户名称" min-width="130" class="ellipsis">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.clientName"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="下单日期" min-width="108" prop="orderTime" sortable="custom">
          <template slot-scope="scope">
            <div class="ellipsis">{{ standardFormatNoHour(scope.row.orderTime, 'YYYY/MM/DD') }}</div>
          </template>
        </el-table-column>
        <el-table-column align="right" label="含税金额(元)" width="130" prop="taxAmount" sortable="custom">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="品牌名称" min-width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.theme"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="达人分成" min-width="90">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.talentOptions && scope.row.isAutoTalent === 1" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 300px;">
                <div style="margin-bottom:5px;">供应商：{{ scope.row.talentOptions.channelName || '--' }}</div>
                <div v-if="scope.row.talentOptions.ruleName" style="margin-bottom:5px;" >{{ scope.row.talentOptions.ruleName || '' }}</div>
                <div style="margin-bottom:5px;">公式：{{ scope.row.talentOptions.formula || '--' }}</div>
                <div>条件：{{ scope.row.talentOptions.condition || '--' }}</div>
              </div>
              <div>自动填写</div>
            </el-tooltip>
            <div v-else-if="scope.row.isAutoTalent === 0">手动填写</div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="备注"
          min-width="87"
          class-name="remark"
        >
          <template slot-scope="scope">
            <ToolTip :content="scope.row.remark"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="订单类型" min-width="80">
          <template slot-scope="scope">
            <div :style="{background: getColorBg(scope.row.orderType).bg || 'rgb(253, 239, 233)', color: getColorBg(scope.row.orderType).color || 'rgb(253, 133, 70)'}" class="order-type">
              {{ scope.row.orderType | orderTypeStatusFilter }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="订单状态" min-width="100">
          <template slot-scope="scope">
            <div class="dot-wrap">
              <span :style="{backgroundColor: getOrderColor(scope.row.orderStatus)}" class="dot"/>
              {{ scope.row.orderStatus | setOrderState }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="核销状态" min-width="100">
          <template slot-scope="scope">
            <div class="dot-wrap">
              <span :style="{backgroundColor: scope.row.accountState ? '#999':'#406EFF'}" class="dot"/>
              {{ scope.row.accountState | setAccountState }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="!isRecheck" align="center" label="审批状态" min-width="98">
          <template slot-scope="scope">
            <div v-if="scope.row.reviewState || scope.row.reviewState === 0" class="dot-wrap">
              <span :style="{backgroundColor: getColor(scope.row.reviewState)}" class="dot"/>
              {{ scope.row.reviewState | setSealReviewState }}
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column v-if="!isRecheck" :width="showMobilePage ? 50 : 'auto'" min-width="100" align="center" label="操作" fixed="right">
          <template slot-scope="scope">
            <div v-if="!showMobilePage" class="review-setting-btn">
              <div class="review-setting">
                <el-button type="text" size="small" style="padding: 0" @click="toCheck(scope)">
                  <div style="display: flex; align-items: center; height: 16px;">
                    <span style="margin-right: 4px">记录</span>
                  </div>
                </el-button>
                <el-button
                  v-if="!isReport"
                  :disabled="scope.row.orderType === 2 || scope.row.reviewState === 1 || !hasRouteAuth('crm:finance:sellFirstTrial') || scope.row.isHedging"
                  type="text"
                  size="small"
                  style="margin: 0;padding: 0"
                  @click="toEdit(scope)"
                >
                  <div style="display: flex; align-items: center; height: 16px;">
                    <span style="color: #406EFF;margin: 1px 5px 0 0;transform: scaleY(0.8);">|</span>
                    <span style="margin-right: 4px">编辑</span>
                  </div>
                </el-button>
              </div>
            </div>
            <tableOperateBtn v-else>
              <el-dropdown-item @click.native="toCheck(scope)">
                <div style="font-size: 14px">审批记录</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="!isReport" :disabled="scope.row.orderType === 2 || scope.row.reviewState === 1 || !hasRouteAuth('crm:finance:sellFirstTrial') || scope.row.isHedging" @click.native="toEdit(scope)">
                <div style="font-size: 14px">订单编辑</div>
              </el-dropdown-item>
            </tableOperateBtn>
          </template>
        </el-table-column>
        <el-table-column v-else :width="showMobilePage ? 50 : (hasRouteAuth('crm:finance:financeRecheck') ? 220 : 90)" align="center" label="操作" fixed="right">
          <template slot-scope="scope">
            <reviewColumn :is-recheck="isRecheck" :is-report="isReport" :item="scope.row" :sealing-id="sealingId" :column-type="'order'" @freshData="getData" />
          </template>
        </el-table-column>
      </el-table>

      <fixed-pagination v-show="list.total > 0" :class="{'position-b56': !showMobilePage, 'position-b49': showMobilePage}" class="center">
        <div style="flex:1;display:flex;">
          <tableFooterBtn
            v-if="!isReport"
            ref="tableFooterBtn"
            :select-data="multipleSelection"
            :process-state="processState"
            :sealing-id="sealingId"
            :multiple-selection-all="multipleSelectionAll"
            column-type="order"
            @clearMixinSelection="clearMixinSelection"
            @queryClick="queryClick"
            @refreshData="refreshData" />
        </div>
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="showMobilePage ? pageLayout : 'total, prev, pager, next, sizes'"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </fixed-pagination>
    </div>
  </div>
</template>
<script>
import orderEdit from '@/assets/order-edit.png';
import defaultEdit from '@/assets/defalut-edit.png';
import orderDetail from '@/assets/order-detail.png';

import reviewColumn from '../reviewColumn';
import tableFooterBtn from '../tableFooterBtn';

import { getSealOrderList } from '@/api/sealingAccount';
import { standardFormatNoHour } from '@/filters/date';
import { colorList } from './colorData';
import {
  orderTypeStatusFilter,
  setAccountState,
  setSealReviewState,
  setOrderState
} from '@/filters/status';
import ExportButton from '@/components/ExportButton';
import topRightAmount from '../topRightAmount';
import { hasRouteAuth } from '@/utils/permission';
import { paramsFormat } from '@/utils/paramsFormat';
import SealingMixins from '@/components/Finance/mixins/sealing';
import paramsDateFormat from '@/mixins/paramsDateFormat';
import tableSelections from '@/mixins/tableSelections';
import costSet from '@/mixins/costSet';
import { verificationOptions } from '@/views/project/model/selectData';
import mobileTable from '@/mixins/mobileTable';
import { PROCESS_STATE } from '@/utils/const/sealing';
import exportImg from '@/assets/export.png';

export default {
  name: 'OrderTable',
  filters: {
    orderTypeStatusFilter,
    setAccountState,
    setSealReviewState,
    setOrderState
  },
  components: { ExportButton, topRightAmount, reviewColumn, tableFooterBtn },
  mixins: [SealingMixins, paramsDateFormat, costSet, tableSelections, mobileTable],
  props: {
    // true：复审，false：初审
    isRecheck: {
      type: Boolean,
      default: false
    },
    // true: 初审/复审，false：查看报告
    isReport: {
      type: Boolean,
      default: true
    },
    sealingId: {
      type: Number,
      default: null
    },
    processState: {
      type: Number | String,
      default: PROCESS_STATE.REVIEW
    }
  },
  data() {
    return {
      orderEdit, defaultEdit, orderDetail, colorList,
      exportImg,
      listLoading: false,
      paramsObj: {},
      filterList: [
        // select
        { keyword: 'accountState', name: '核销状态', type: 'select', options: verificationOptions },
        { keyword: 'reviewStateFilter', name: '审批状态', type: 'select', options: [
          { value: 0, label: '待审批' },
          { value: 1, label: '已通过' }, { value: 2, label: '未过审' }]
        },
        { keyword: 'orderType', name: '订单类型', type: 'select', options: [
          { value: 0, label: '原订单' },
          { value: 2, label: '对冲单' }, { value: 4, label: '补录单' },
          { value: 5, label: '调整单' }, { value: 7, label: '补差单' }]
        },
        // input
        { keyword: 'orderId', name: '订单编号', type: 'input' },
        { keyword: 'clientName', name: '客户名称', type: 'input' },
        { keyword: 'theme', name: '品牌名称', type: 'input' },
        { keyword: 'remark', name: '备注', type: 'input' },
        { keyword: 'createTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate' }
      ],
      multipleSelection: [],
      isSealing: false,
      sortType: '',
      sortName: '',
      tableRefName: 'orderTableRef',
      page: 1,
      perPage: 20,
      list: {},
      dateDataAttrName: [
        {
          attr: 'createTime',
          start: 'createStart',
          end: 'createEnd',
          endType: 1
        }
      ]
    };
  },
  methods: {
    hasRouteAuth,
    standardFormatNoHour,
    getData(reset) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      if (this.isBatchAll) params.returnIds = true;
      this.listLoading = true;
      getSealOrderList(params, this.sealingId).then(res => {
        if (this.isBatchAll) {
          // 批量操作事件 先根据条件搜索出对应的id数组，再将id集合传送给操作接口
          this.operateHandle(this.requestType, res);
        } else {
          this.listLoading = false;
          this.list = res.data;
        }
        this.isBatchAll = false;
        this.setSelectRow && this.setSelectRow(res.data.items);
      }).catch(err => {
        this.isBatchAll = false;
        this.listLoading = false;
        console.error(err);
      });
    },
    // 多选
    tableSelectionChange(e) {
      this.ids = e.map(item => item.id).join(',');
    },
    formatParams(sendPageConfig = true) {
      const { sortName, sortType, paramsObj, dateDataAttrName, page, perPage,
        processState, sealingId } = this;
      let params = JSON.parse(JSON.stringify(paramsObj));
      // 时间处理
      this.paramsDateFormat(dateDataAttrName, params, 's');
      // 参数处理
      params = paramsFormat(params);
      if (sendPageConfig) {
        params.page = page;
        params.perPage = perPage;
      }
      if (sortName) {
        params.sortName = sortName;
        params.sortType = sortType;
      }
      params.processState = processState;
      params.id = sealingId;
      params.timeType = 0;
      return params;
    },
    toCheck(scope) {
      const url = this.$router.resolve({
        name: 'sealingAccountDetail',
        params: { sealingAccountId: scope.row.id },
        query: { type: 0 }
      });
      window.open(url.href, '_blank');
    },
    toEdit(scope) {
      this.$router.push({
        name: 'editOrder',
        params: { orderId: scope.row.id },
        query: { sealingId: this.sealingId }
      });
    },
    getColorBg(type) {
      // 订单类型
      const orderTypeImg = [{
        type: 0,
        bg: '#EFF4FF',
        color: '#406EFF'
      }, {
        type: 1,
        bg: '#E2F8F2',
        color: '#31CC9C'
      }, {
        type: 2,
        bg: '#FFEFF0',
        color: '#FF4E5F'
      }, {
        type: 3,
        bg: '#F9ECFF',
        color: '#9B5BED'
      }, {
        type: 4,
        bg: '#FFF8EA',
        color: '#FFBC3D'
      }, {
        type: 5,
        bg: '#FFF2EB',
        color: '#FD8546'
      }, {
        type: 6,
        bg: '#FDEFE9',
        color: '#FD8546'
      }, {
        type: 7,
        bg: '#FFE6F2',
        color: '#F861AD'
      }];
      return orderTypeImg.find(theme => type === theme.type) || {};
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/styles/placeholder.scss';
.dot-wrap {
  @extend %dot-wrap;
}
.seal-order-content {
  .seal-order-table {
    .el-table {
      color: #999 !important;
      .review-state {
        width: 88px;
        height: 26px;
        border-radius: 16px;
        text-align: center;
        line-height: 26px;
        margin: 0 auto;
        .icon-class {
          width: 16px;
          height: 16px;
        }
      }
      .sealing-pass {
        width: 48px;
        height: 26px;
        line-height: 2px;
        background: #406EFF;
        border-radius: 16px;
        color: #fff;
      }
      .sealing-fail {
        width: 48px;
        height: 26px;
        line-height: 2px;
        background: #EFF3FB;
        border-radius: 13px;
        color: #406EFF;
      }
      .pass-color {
        color: #31CC9C;
      }
      .fail-color {
        color: #E02020;
      }
      &::v-deep {
        th .el-checkbox {
          margin: 0 4px;
        }
      }
    }
  }
}
@import '@/styles/placeholder.scss';
.export-wrap {
  @extend %sealing-export-btn;
}
.order-type {
    padding: 0 5px;
    height: 24px;
    border-radius: 16px;
    display: flex;
    font-size: 14px;
    justify-content: center;
    align-content: center;
    align-items: center;
    img {
      width: 16px;
      height: 16px;
      margin-right: 6px;
    }
  }
.review-setting {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
